package com.sardine.base.esm.session;

import com.sardine.base.esm.dataSource.EsmDataSource;
import com.sardine.base.esm.mapping.EsmEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import java.io.IOException;

import static org.springframework.util.Assert.notNull;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/5/22
 * Time:10:18
 * 构建 EsmSession bean的工厂类
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class EsmSessionFactoryBean implements FactoryBean<EsmSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
    private static final Logger logger = LoggerFactory.getLogger(EsmSessionFactoryBean.class);
    private String environment = EsmSessionFactoryBean.class.getSimpleName();
    /**
     * 数据源
     */
    private EsmDataSource dataSource;
    /**
     * 具体实现
     */
    private EsmSessionFactory sessionFactory;
    /**
     * EsmSessionFactory builder
     */
    private EsmSessionFactoryBuilder esmSessionFactoryBuilder = new EsmSessionFactoryBuilder();

    public EsmDataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(EsmDataSource dataSource) {
        this.dataSource = dataSource;
    }



    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        logger.info("构建 EsmSession bean的工厂类:ApplicationListener");
    }

    @Override
    public EsmSessionFactory getObject() throws Exception {
        if (this.sessionFactory == null) {
            afterPropertiesSet();
        }
        return this.sessionFactory;
    }


    @Override
    public Class<?> getObjectType() {
        return this.sessionFactory == null ? EsmSessionFactory.class : this.sessionFactory.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    /**
     * 校验  dataSource 是否配置
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        notNull(dataSource, "Property 'dataSource' is required");
        //构建 EsmSessionFactory
        this.sessionFactory = buildEsmSessionFactory();
    }

    /**
     * 创建 EsmSessionFactory 对象
     * @return
     * @throws IOException
     */
    protected EsmSessionFactory buildEsmSessionFactory() throws IOException {
        //esm 的配置对象
        Configuration configuration=new Configuration();
        EsmEnvironment esmEnvironment = new EsmEnvironment(this.environment,dataSource);
        //设置环境信息
        configuration.setEsmEnvironment(esmEnvironment);
        //构建 EsmSessionFactory
       return esmSessionFactoryBuilder.build(configuration);
    }

}
